#!/usr/local/bin/python
# ex) python client.py test cpu 99

import xmlrpclib, pickle, time, sys, os
from types import *

FN="/tmp/"+os.path.basename(sys.argv[0])+".dat"

def formatExceptionInfo(maxTBlevel=5):
        import sys, traceback
        cla, exc, trbk = sys.exc_info()
        excName = cla.__name__
        try:
                excArgs = exc.__dict__["args"]
        except KeyError:
                excArgs = "<no args>"
        excTb = traceback.format_tb(trbk, maxTBlevel)
        return (excName, excArgs, excTb)

try:
        s = xmlrpclib.Server('http://10.10.209.109:8080/sysusage/xmlrpc')

        if len(sys.argv) == 4:
                hostname = sys.argv[1]
                property = sys.argv[2]
                value    = int(float(sys.argv[3]))

                print len(sys.argv), hostname, property, value

                s.Gather.insert_rawdata(hostname, property, value)
        elif len(sys.argv) == 5:
                hostname = sys.argv[1]
                property = sys.argv[2]
                value    = int(float(sys.argv[3]))
                timestamp= sys.argv[4]

                print len(sys.argv), hostname, property, value, timestamp

                s.Gather.insert_rawdata(hostname, property, value, timestamp)
        else:
                print "ERROR: len(sys.argv) == %d" % len(sys.argv)

        file(FN, 'a')
        if os.path.getsize(FN) != 0:
                ar = pickle.load(file(FN, 'rb'))

                while len(ar) > 0:
                        i = ar.pop()
                        print "Queue: %s,%s,%s,%s" % (i[0], i[1], i[2], i[3])
                        s.Gather.insert_rawdata(i[0], i[1], int(float(i[2])), i[3])

                pickle.dump(ar, file(FN,'wb'))
except:
        import pprint
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(formatExceptionInfo())
        print "================================"

        ar = []

        if os.path.getsize(FN) != 0:
                ar = pickle.load(file(FN, 'rb'))
        if len(sys.argv) == 4:
                sys.argv.append(time.strftime('%Y-%m-%d %H:%M:%S'))
        ar.append(sys.argv[1:])

        pickle.dump(ar, file(FN,'wb'))
        print ar
        